import os
import zipfile
import paramiko

print('开始部署')
def zip_folder(folder_path, zip_filename):
    with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for root, dirs, files in os.walk(folder_path):
            for file in files:
                file_path = os.path.join(root, file)
                zipf.write(file_path, os.path.relpath(file_path, folder_path))
print('部署中')
def upload_and_unzip(zip_filename, local_folder_path, remote_folder_path, hostname, username, password):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname, username=username, password=password)
    sftp = ssh.open_sftp()

    # 上传 ZIP 文件
    sftp.put(zip_filename, os.path.join(remote_folder_path, os.path.basename(zip_filename)))

    # 在服务器上解压 ZIP 文件
    command = f"unzip -o {os.path.join(remote_folder_path, os.path.basename(zip_filename))} -d {remote_folder_path}"
    stdin, stdout, stderr = ssh.exec_command(command)
    stdout.read().decode()
    stderr.read().decode()

    sftp.close()
    ssh.close()
    print('部署成功')

# 使用示例
local_folder = './.output/'
zip_filename = 'your_folder.zip'
remote_folder = '/usr/local/nginx/html/nuxt-demo/'
hostname = '47.121.176.38'
username = 'root'
password = 'Qq130731010743'

# local_folder = './.output/'
# zip_filename = 'your_folder.zip'
# remote_folder = '/usr/local/program/nginx/html/nuxt-demo/'
# hostname = '192.168.3.12'
# username = 'root'
# password = 'ASixOsRoot'

zip_folder(local_folder, zip_filename)
upload_and_unzip(zip_filename, local_folder, remote_folder, hostname, username, password)

# 清理本地生成的 ZIP 文件
os.remove(zip_filename)
